/**
 * 初始化 bs-wyswyg 的封装
 */
(function() {
	var BsEditor = function(editorDOMId, extraConfig) {
		this.editorDOMId = editorDOMId;
		this.editorDOM = null;
		this.contentDOM = null;

		this.extraConfig = extraConfig;

		this.init();
	};


	BsEditor.prototype = {
		/**
		 * 初始化 bs-wyswyg
		 */
		init: function() {
			var self = this;
			var editorId = self.editorDOMId;
			self.editorDOM = $("#" + editorId);

			var contentDOMId = "BsEditor_content_" + self.editorDOMId;
			var contentHTML = '<div id="' + contentDOMId + '" class="web-content"></div>';

			if(!self.editorDOM.hasClass("web-edit-div"))
				self.editorDOM.addClass("web-edit-div");

			var TOOL_BACK_HTML = '<div class="btn-toolbar-back hidden"></div>';

			var TOOL_BAR_HTML = '<div class="btn-toolbar" data-role="editor-toolbar" data-target="#inputContent">' +
				'<div class="btn-group">' +
				'<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="字体"><i class="fa fa-font"></i><b class="caret"></b></a>' +
				'<ul id="fontDropdown" class="dropdown-menu">' +
				'</ul>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="字号"><i class="fa fa-text-height"></i>&nbsp;<b class="caret"></b></a>' +
				'<ul class="dropdown-menu">' +
				'<li>' +
				'<a data-edit="fontSize 5">' +
				'<font size="5">大号</font>' +
				'</a>' +
				'</li>' +
				'<li>' +
				'<a data-edit="fontSize 3">' +
				'<font size="3">中号</font>' +
				'</a>' +
				'</li>' +
				'<li>' +
				'<a data-edit="fontSize 1">' +
				'<font size="1">小号</font>' +
				'</a>' +
				'</li>' +
				'</ul>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" data-edit="bold" title="加粗 (Ctrl/Cmd+B)"><i class="fa fa-bold"></i></a>' +
				'<a class="btn btn-default" data-edit="italic" title="斜体 (Ctrl/Cmd+I)"><i class="fa fa-italic"></i></a>' +
				'<a class="btn btn-default" data-edit="strikethrough" title="中划线"><i class="fa fa-strikethrough"></i></a>' +
				'<a class="btn btn-default" data-edit="underline" title="下划线 (Ctrl/Cmd+U)"><i class="fa fa-underline"></i></a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" data-edit="insertunorderedlist" title="无序列表"><i class="fa fa-list-ul"></i></a>' +
				'<a class="btn btn-default" data-edit="insertorderedlist" title="有序列表"><i class="fa fa-list-ol"></i></a>' +
				'<a class="btn btn-default" data-edit="outdent" title="缩小缩进 (Shift+Tab)"><i class="fa fa-outdent"></i></a>' +
				'<a class="btn btn-default" data-edit="indent" title="缩进 (Tab)"><i class="fa fa-indent"></i></a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" data-edit="justifyleft" title="居左对齐 (Ctrl/Cmd+L)"><i class="fa fa-align-left"></i></a>' +
				'<a class="btn btn-default" data-edit="justifycenter" title="居中对齐 (Ctrl/Cmd+E)"><i class="fa fa-align-center"></i></a>' +
				'<a class="btn btn-default" data-edit="justifyright" title="居右对齐 (Ctrl/Cmd+R)"><i class="fa fa-align-right"></i></a>' +
				'<a class="btn btn-default" data-edit="justifyfull" title="两端对其 (Ctrl/Cmd+J)"><i class="fa fa-align-justify"></i></a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="超链接"><i class="fa fa-link"></i></a>' +
				'<div class="dropdown-menu input-append">' +
				'<input class="span2" placeholder="URL" type="text" data-edit="createLink" />' +
				'<button class="btn btn-default" type="button">Add</button>' +
				'</div>' +
				'<a class="btn btn-default" data-edit="unlink" title="取消链接"><i class="fa fa-cut"></i></a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" title="插入图片 (或复制  & 粘帖)" id="pictureBtn"><i class="fa fa-file-image-o"></i>' +
				'<input type="file" data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage" />' +
				'</a>' +
				'<a class="btn btn-default" title="插入多个图片 (或复制  & 粘帖)" id="picturesBtn"><i class="fa fa-files-o"></i>' +
				'<input type="file" multiple="multiple" data-role="magic-overlay" data-target="#picturesBtn" data-edit="insertImages" />' +
				'</a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" data-edit="undo" title="撤销 (Ctrl/Cmd+Z)"><i class="fa fa-undo"></i></a>' +
				'<a class="btn btn-default" data-edit="redo" title="重做 (Ctrl/Cmd+Y)"><i class="fa fa-repeat"></i></a>' +
				'</div>' +
				'<div class="btn-group">' +
				'<a class="btn btn-default" data-edit="clearhtml" title="清除HTML代码"><i class="fa fa-paint-brush"></i></a>' +
				'</div>' +
				'<input type="text" data-edit="inserttext" id="voiceBtn_' + self.editorDOMId + '" x-webkit-speech="">' +
				'</div>';
			self.editorDOM.append(TOOL_BACK_HTML);
			self.editorDOM.append(TOOL_BAR_HTML);
			self.editorDOM.append(contentHTML);

			self.contentDOM = $("#" + contentDOMId);

			self.initToolbarBootstrapBindings();

			self.contentDOM.wysiwyg({
				fileUploadError: self.showErrorAlert
			});

			// 判断当前编辑器是否在 Modal 中
			var modalParents = self.editorDOM.parents(".modal");
			if(modalParents.length > 0) {
				var modalParent = modalParents[0];
				// 设置编辑区的菜单栏在滚动保持在顶部位置的监听事件
				/*
				$(modalParent).on("hide.bs.modal", function() {
					$(modalParent).unbind('scroll');
					self.resetToolBarToTop(contentDOMId);
				});
				$(modalParent).on("shown.bs.modal", function() {
					$(modalParent).on('scroll', function() {
						self.bindToolBarInTop(contentDOMId);
					})
				});
				*/
			}

			return this;
		},

		//初始化工具栏
		initToolbarBootstrapBindings: function() {
			var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
					'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
					'Times New Roman', 'Verdana'
				],
				fontTarget = $('#fontDropdown');
			$.each(fonts, function(idx, fontName) {
				fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
			});
			$('a[title]').tooltip({
				container: 'body'
			});
			$('.dropdown-menu input').click(function() {
					return false;
				})
				.change(function() {
					$(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
				})
				.keydown('esc', function() {
					this.value = '';
					$(this).change();
				});

			$('[data-role=magic-overlay]').each(function() {
				var overlay = $(this),
					target = $(overlay.data('target'));
				overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width("100%").height("100%");
			});
			if("onwebkitspeechchange" in document.createElement("input")) {
				var editorOffset = $('#inputContent').offset();
				$('#voiceBtn_' + this.editorDOMId).css('position', 'absolute').offset({
					top: editorOffset.top,
					left: editorOffset.left + $('#editor').innerWidth() - 35
				});
			} else {
				$('#voiceBtn_' + this.editorDOMId).hide();
			}
		},
		//错误提示
		showErrorAlert: function(reason, detail) {
			var msg = '';
			if(reason === 'unsupported-file-type') {
				msg = "Unsupported format " + detail;
			} else {
				console.log("error uploading file", reason, detail);
			}
			$('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>' +
				'<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts');
		},
		/**
		 * 重置 ToolBar 到顶部位置
		 * @param {Object} contentId
		 */
		resetToolBarToTop: function(contentId) {
			var toolBarDivDOM = $("#" + contentId).prev();
			if(toolBarDivDOM != null && toolBarDivDOM.length > 0) {
				var toolBarBackDOM = toolBarDivDOM.prev();
				toolBarDivDOM.css({
					"position": "relative",
					"top": 0
				});
				if(toolBarBackDOM != null && toolBarBackDOM.length > 0) {
					toolBarBackDOM.addClass("hidden");
				}
			}
		},

		/**
		 * 将 ToolBar 绑定在顶部位置
		 * @param {Object} contentId
		 */
		bindToolBarInTop: function(contentId) {
			var webDivDOM = $("#" + contentId).parent();
			var toolBarDivDOM = $("#" + contentId).prev();
			if(webDivDOM != null && webDivDOM.length > 0 &&
				toolBarDivDOM != null && toolBarDivDOM.length > 0) {
				var toolBarBackDOM = toolBarDivDOM.prev();

				var divTop = webDivDOM.offset().top;
				if(divTop < 0) {
					// 当前编辑区域超出屏幕可视区域
					var scrollTop = Math.abs(divTop);
					// 设置工具栏在页面最顶部
					toolBarDivDOM.css({
						"position": "absolute",
						"top": scrollTop + "px"
					});
					if(toolBarBackDOM != null && toolBarBackDOM.length > 0) {
						toolBarBackDOM.removeClass("hidden").css("height", toolBarDivDOM.outerHeight());
					}
				} else {
					toolBarDivDOM.css({
						"position": "relative",
						"top": 0
					});
					if(toolBarBackDOM != null && toolBarBackDOM.length > 0) {
						toolBarBackDOM.addClass("hidden");
					}
				}
			}
		},

		html: function(value) {
			var self = this;
			if(value != null && typeof(value) != "undefined") {
				self.contentDOM.html(value);
			}
			return self.contentDOM.html();
		},

		clearHtml: function() {
			var self = this;

			var html = self.html();
			html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, '');
			html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, '');
			html = _formatHtml(html, {
				a: ['href', 'target'],
				embed: ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
				img: ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'],
				table: ['border'],
				'td,th': ['rowspan', 'colspan'],
				'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': []
			});
			self.html(html);
		},

	}

	window.BsEditor = BsEditor;
}());